<?php
/**
 * +-------------------------------------------------------------
 * |Caption:
 * +-------------------------------------------------------------
 * |Author: Lenny
 * +-------------------------------------------------------------
 * |Email:  1685964109@qq.com
 * +-------------------------------------------------------------
 * |Date:   2024/6/20 上午10:30
 * +-------------------------------------------------------------
 */

namespace app\admin\model;

use app\common\constants\MenuConstant;
use app\common\model\BaseModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class SysMenu extends BaseModel
{

    protected $deleteTime = 'delete_time';

    public function getMenuList(): array
    {
        return $this->field('id,pid,href,title,type')
                    ->where('status',1)
                    ->select()
                    ->toArray();
    }

    /**
     * 获取父级菜单信息
     * @param $pid
     * @return array|mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getPidMenu($pid): mixed
    {
        return $this->find($pid);
    }

    /**
     * 获取菜单列表
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getPidMenuList(): array
    {
        $list        = $this->field('id,pid,title')
                            ->where([
                                            ['status', '=', 1],
                                            ['type', '=', MenuConstant::MENU_TYPE]
                                    ])
                            ->select()
                            ->toArray();
        $pidMenuList = $this->buildPidMenu(0, $list);

        return array_merge( [[
                                            'id'    => 0,
                                            'pid'   => 0,
                                            'title' => '顶级菜单',
                                    ]], $pidMenuList);
    }

    /**
     * 递归生成菜单
     * @param $pid
     * @param $list
     * @param $level
     * @return array
     */
    protected function buildPidMenu($pid, $list, $level = 0): array
    {
        $newList = [];
        foreach ($list as &$vo) {
            if ($vo['pid'] == $pid) {
                $level++;
                foreach ($newList as $v) {
                    if ($vo['pid'] == $v['pid'] && isset($v['level'])) {
                        $level = $v['level'];
                        break;
                    }
                }
                $vo['level'] = $level;
                $menu = $vo;
                $childList = $this->buildPidMenu($vo['id'], $list, $level);
                if(!empty($childList)){
                    $menu['child'] = $childList;
                }
                $newList[] = $menu;
            }

        }
        return $newList;
    }
}